package com.zx.BookSeaReader.greendao.service;

import android.database.Cursor;

import com.zx.BookSeaReader.entity.bookstore.BookType;
import com.zx.BookSeaReader.greendao.GreenDaoManager;
import com.zx.BookSeaReader.greendao.entity.Book;
import com.zx.BookSeaReader.greendao.entity.SubscribeBean;
import com.zx.BookSeaReader.greendao.entity.UserBean;
import com.zx.BookSeaReader.greendao.gen.BookDao;
import com.zx.BookSeaReader.greendao.gen.BookTypeDao;
import com.zx.BookSeaReader.greendao.gen.SubscribeBeanDao;
import com.zx.BookSeaReader.greendao.gen.UserBeanDao;
import com.zx.BookSeaReader.util.Constant;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.UUID;


public class BookService extends BaseService {

    private ChapterService mChapterService;
    private UserService mUserService;

    public BookService(){
        mChapterService = new ChapterService();
        mUserService =new UserService();
    }

    private List<Book> findBooks(String sql, String[] selectionArgs) {
        ArrayList<Book> books = new ArrayList<>();
        try {
            Cursor cursor = selectBySql(sql, selectionArgs);
            while (cursor.moveToNext()) {
                Book book = new Book();
                book.setId(cursor.getString(0));
                book.setName(cursor.getString(1));
                book.setChapterUrl(cursor.getString(2));
                book.setImgUrl(cursor.getString(3));
                book.setDesc(cursor.getString(4));
                book.setAuthor(cursor.getString(5));
                book.setType(cursor.getString(6));
                book.setUpdateDate(cursor.getString(7));
                book.setNewestChapterId(cursor.getString(8));
                book.setNewestChapterTitle(cursor.getString(9));
                book.setNewestChapterUrl(cursor.getString(10));
                book.setHistoryChapterId(cursor.getString(11));
                book.setHisttoryChapterNum(cursor.getInt(12));
                book.setSortCode(cursor.getInt(13));
                book.setNoReadNum(cursor.getInt(14));
                book.setChapterTotalNum(cursor.getInt(15));
                book.setLastReadPosition(cursor.getInt(16));
                book.setSource(cursor.getString(17));
                books.add(book);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return books;
    }

    /**
     * 通过ID查书
     * @param id
     * @return
     */
    public Book getBookById(String id) {
        BookDao bookDao = GreenDaoManager.getInstance().getSession().getBookDao();
        return bookDao.load(id);
    }
    /**
     * @Author: ZX
     * @Time: 2020/2/15
     * @Description: 该书籍是否存在
     */
    public boolean existBook(String bookid){
        BookDao bookDao = GreenDaoManager.getInstance().getSession().getBookDao();
        List<Book> books=bookDao.queryBuilder()
                .where(BookDao.Properties.Id.eq(bookid))
                .list();
        if(books.size()>0){
            return true;
        }else {
            return false;
        }

    }

    /**
     * @Author: ZX
     * @Time: 2020/2/15
     * @Description: 查询缓存列表
     */
    public List<Book> getDownloadBooks(){
        BookDao bookDao = GreenDaoManager.getInstance().getSession().getBookDao();
        List<Book> books=bookDao.queryBuilder()
                .where(BookDao.Properties.Recommend.eq(9))
                .list();
        if(books.size()>0){
            return books;
        }else {
            books=new ArrayList<>();
            return books;
        }

    }


    /**
     * 获取所有的书
     * @return
     */
    public List<Book> getAllBooks(){
        String sql = "select * from book  order by sort_code";
        return findBooks(sql, null);
    }

    /**
     * 获取所有的书
     * @return
     */
    public List<Book> getAllBook(){
        BookDao bookDao = GreenDaoManager.getInstance().getSession().getBookDao();
        List<Book> books=bookDao.queryBuilder().list();
        return books;
    }



    /**
     * 获取订阅的书
     * @return
     */
    public List<Book> getSubBook(String username){
        UserBean user=mUserService.getUser(username);
        List<Book> books=user.getBooks();
        ListSort(books);
        return books;
    }

    /**
     * @Author: ZX
     * @Time: 2020/2/15
     * @Description: 时间排序
     */
    private static void ListSort(List<Book> list) {
        Collections.sort(list, new Comparator<Book>() {
            @Override
            public int compare(Book o1, Book o2) {
                SimpleDateFormat format = new SimpleDateFormat(Constant.FORMAT_BOOK_DATE);
                try {
                    Date dt1 = format.parse(o1.getLastRead());
                    Date dt2 = format.parse(o2.getLastRead());
                    if (dt1.getTime() < dt2.getTime()) {
                        return 1;
                    } else if (dt1.getTime() > dt2.getTime()) {
                        return -1;
                    } else {
                        return 0;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return 0;
            }
        });
    }



    /**
     * 按照List中的某个String类型的属性进行排序
     * @param list
     */
    @SuppressWarnings("unchecked")
    public static void sortStringMethod(List<Book> list) {
        Collections.sort(list, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                Book stu1 = (Book) o1;
                Book stu2 = (Book) o2;
                return stu1.getLastRead().compareTo(stu2.getLastRead());
            }
        });
    }


        /**
         * 新增书连接
         * @param
         */
    public void addSubscribe(String bookid, UserBean userbean){
        SubscribeBean subscribeBean=new SubscribeBean();
        subscribeBean.setBookid(bookid);
        subscribeBean.setUserid(userbean.getUserid());
        SubscribeBeanDao subscribeBeanDao = GreenDaoManager.getInstance().getSession().getSubscribeBeanDao();
        subscribeBeanDao.insert(subscribeBean);
    }

    /**
     * 新增书
     * @param book
     */
    public void addBook(Book book){
        book.setSortCode(countBookTotalNum() + 1);
      //  book.setId(UUID.randomUUID().toString());
        addEntity(book);
    }
    /**
     * 新增书2
     * @param book
     */
    public void addBookAndSub(Book book,UserBean user){
        book.setIsLocal(false);
        book.setIsCollect(true);
        book.setSortCode(countBookTotalNum() + 1);
        addSubscribe(book.getId(),user);
        addEntity(book);
    }

    /**
     * 是否订阅
     * @param book
     */
    public boolean isSubscribe(Book book,UserBean user){
        SubscribeBeanDao subscribeBeanDao = GreenDaoManager.getInstance().getSession().getSubscribeBeanDao();
        List<SubscribeBean> subscribeBeans=subscribeBeans=subscribeBeanDao.queryBuilder()
                .where(SubscribeBeanDao.Properties.Bookid.eq(book.getId()),SubscribeBeanDao.Properties.Userid.eq(user.getUserid()))
                .list();
        if(subscribeBeans.size()>0){
            return true;
        }else {
            return false;
        }
    }


    /**
     * 查找书（作者、书名）
     * @param author
     * @param bookName
     * @return
     */
    public Book findBookByAuthorAndName(String bookName, String author){
        BookDao bookDao = GreenDaoManager.getInstance().getSession().getBookDao();
        Book book=null;
        List<Book> books= bookDao.queryBuilder()
                .where(BookDao.Properties.Name.eq(bookName),BookDao.Properties.Author.eq(author))
                .list();
        if(books.size()>0){
            return books.get(0);
        }else {
            return book;
        }
    }

    /**
     * @Author: ZX
     * @Time: 2020/2/15
     * @Description: 获得书籍
     */
    public UserBean getUser(String username){
        UserBeanDao userBeanDao = GreenDaoManager.getInstance().getSession().getUserBeanDao();
        return userBeanDao.queryBuilder()
                .where(UserBeanDao.Properties.Username.eq(username))
                .unique();

    }



    /**
     * 删除书
     * @param id
     */
    public void deleteBookById(String id){
        BookDao bookDao = GreenDaoManager.getInstance().getSession().getBookDao();
        bookDao.deleteByKey(id);
        mChapterService.deleteBookALLChapterById(id);
    }


    /**
     * 删除书和订阅
     * @param id
     */
    public void deleteBookAndSub(String id,UserBean userBean){
        SubscribeBeanDao subscribeBeanDao = GreenDaoManager.getInstance().getSession().getSubscribeBeanDao();
        SubscribeBean subscribeBean =new SubscribeBean();
        subscribeBean=subscribeBeanDao.queryBuilder()
                .where(SubscribeBeanDao.Properties.Bookid.eq(id),SubscribeBeanDao.Properties.Userid.eq(userBean.getUserid()))
                .unique();
        subscribeBeanDao.delete(subscribeBean);
        BookDao bookDao = GreenDaoManager.getInstance().getSession().getBookDao();
        bookDao.deleteByKey(id);
    }

    /**
     * 取消订阅
     * @param id
     */
    public void deleteSub(String id,UserBean userBean){
        SubscribeBeanDao subscribeBeanDao = GreenDaoManager.getInstance().getSession().getSubscribeBeanDao();
       // SubscribeBean subscribeBean =new SubscribeBean();
        List<SubscribeBean> subscribeBeans=subscribeBeanDao.queryBuilder()
                .where(SubscribeBeanDao.Properties.Bookid.eq(id),SubscribeBeanDao.Properties.Userid.eq(userBean.getUserid()))
                .list();
        subscribeBeanDao.deleteInTx(subscribeBeans);
    }

    /**
     * 删除用户所有订阅
     * @param
     */
    public void deleteAllSub(UserBean userBean){
        SubscribeBeanDao subscribeBeanDao = GreenDaoManager.getInstance().getSession().getSubscribeBeanDao();
        List<SubscribeBean> subscribeBeans=subscribeBeanDao.queryBuilder()
                .where(SubscribeBeanDao.Properties.Userid.eq(userBean.getUserid()))
                .list();
        subscribeBeanDao.deleteInTx(subscribeBeans);
    }



    /**
     * 删除书
     * @param book
     */
    public void deleteBook(Book book){
       deleteEntity(book);
        mChapterService.deleteBookALLChapterById(book.getId());
    }

    /**
     * 查询书籍总数
     * @return
     */
    public int countBookTotalNum(){
        int num = 0;
        try {
            Cursor cursor = selectBySql("select count(*) n from book ",null);
            if (cursor.moveToNext()){
                num = cursor.getInt(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return num;
    }

    /**
     * 更新书
     * @param books
     */
    public void updateBooks(List<Book> books){
        BookDao bookDao = GreenDaoManager.getInstance().getSession().getBookDao();
        bookDao.updateInTx(books);
    }
    /**
     * @Author: ZX
     * @Time: 2020/2/15
     * @Description: 增加多本书
     */
    public void addBooks(List<Book> books){
        BookDao bookDao = GreenDaoManager.getInstance().getSession().getBookDao();
        bookDao.insertInTx(books);
    }



    /**
     * 添加书本分类列表
     * @return
     */
    public void addBookTypes(List<BookType> bookTypes){
        BookTypeDao bookTypeDao = GreenDaoManager.getInstance().getSession().getBookTypeDao();
        bookTypeDao.insertInTx(bookTypes);

    }
    /**
     * 添加书本分类列表
     * @return
     */
    public List<BookType> getBookTypes(){
        BookTypeDao bookTypeDao = GreenDaoManager.getInstance().getSession().getBookTypeDao();
        return bookTypeDao.loadAll();

    }
    /**
     * @Author: ZX
     * @Time: 2020/2/15
     * @Description: 该分类是否存在
     */
    public boolean existType(BookType type){
        BookTypeDao bookTypeDao = GreenDaoManager.getInstance().getSession().getBookTypeDao();
        List<BookType> types=bookTypeDao.queryBuilder()
                .where(BookTypeDao.Properties.TypeName.eq(type.getTypeName()))
                .list();
        if(types.size()>0){
            return true;
        }else {
            return false;
        }

    }


}
